<template>
  <div class="user-management-container">
    <!-- 搜索区域 -->
    <el-card class="search-card" shadow="never">
      <el-form :inline="true" :model="searchModel" class="search-form">
        <el-form-item label="员工状态">
          <el-select v-model="searchModel.state" placeholder="请选择状态" clearable style="width: 150px">
            <el-option v-for="item in searchModel.state_list" :key="item.value" :label="item.label"
              :value="item.value" />
          </el-select>
        </el-form-item>

        <el-form-item label="职位角色">
          <el-select v-model="searchModel.role" placeholder="请选择职位" clearable style="width: 150px">
            <el-option v-for="item in searchModel.role_list" :key="item.name" :label="item.name" :value="item.name" />
          </el-select>
        </el-form-item>

        <el-form-item label="员工姓名">
          <el-input v-model="searchModel.username" placeholder="请输入姓名" clearable style="width: 200px" />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="getUserList" icon="el-icon-search">查询</el-button>
          <el-button @click="resetSearch" icon="el-icon-refresh">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 操作按钮区域 -->
    <div class="operation-area">
      <el-button type="success" @click="openEditUI(null)" icon="el-icon-plus">新增员工</el-button>
    </div>

    <!-- 表格区域 -->
    <el-card class="table-card" shadow="never">
      <el-table :data="userList" stripe style="width: 100%" v-loading="listLoading" border>
        <el-table-column label="序号" width="80" align="center">
          <template slot-scope="scope">
            {{ (searchModel.pageNo - 1) * searchModel.pageSize + scope.$index + 1 }}
          </template>
        </el-table-column>

        <el-table-column prop="username" label="姓名" width="120" align="center" />

        <el-table-column prop="img" label="头像" width="120" align="center">
          <template slot-scope="scope">
            <el-avatar :src="scope.row.head_portrait" :size="60" v-if="scope.row.head_portrait" />
            <el-avatar :size="60" v-else>{{ scope.row.username.charAt(0) }}</el-avatar>
          </template>
        </el-table-column>

        <el-table-column prop="roles.0.name" label="职位" width="150" align="center" />

        <el-table-column prop="state" label="状态" width="100" align="center">
          <template slot-scope="scope">
            <el-tag :type="scope.row.state == 0 ? 'success' : 'danger'" effect="dark">
              {{ scope.row.state == 0 ? '在职' : '离职' }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column prop="gs" label="工时系数" width="120" align="center" />

        <el-table-column label="操作" width="220" align="center" fixed="right">
          <template slot-scope="scope">
            <el-button type="primary" size="mini" @click="openEditUI(scope.row.id)" icon="el-icon-edit">编辑</el-button>
            <el-button type="danger" size="mini" @click="deleteUser(scope.row)" icon="el-icon-delete">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 分页区域 -->
    <div class="pagination-area">
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
        :current-page="searchModel.pageNo" :page-sizes="searchModel.pageSizes" :page-size="searchModel.pageSize"
        layout="total, sizes, prev, pager, next, jumper" :total="total" background />
    </div>

    <!-- 新增/编辑员工弹窗 -->
    <el-dialog :title="title" :visible.sync="dialogFormVisible" width="600px" :close-on-click-modal="false"
      @close="clearForm">
      <el-form :model="userForm" ref="userFormRef" :rules="rules" label-position="left" label-width="100px">
        <el-form-item label="员工姓名" prop="username">
          <el-input v-model="userForm.username" placeholder="请输入员工姓名" clearable />
        </el-form-item>

        <el-form-item v-if="userForm.id == null || userForm.id == undefined" label="登录密码" prop="password">
          <el-input v-model="userForm.password" placeholder="请输入6-20位密码" show-password clearable />
        </el-form-item>

        <el-form-item label="职位角色" prop="role">
          <el-select v-model="userForm.role" placeholder="请选择职位角色" style="width: 100%">
            <el-option v-for="item in searchModel.role_list" :key="item.name" :label="item.name" :value="item.name" />
          </el-select>
        </el-form-item>

        <el-form-item label="状态" prop="state">
          <el-select v-model="userForm.state" placeholder="请选择状态" style="width: 100%">
            <el-option v-for="item in searchModel.state_list" :key="item.value" :label="item.label"
              :value="item.value" />
          </el-select>
        </el-form-item>

        <el-form-item label="工时系数" prop="gs">
          <el-input v-model="userForm.gs" placeholder="请输入工时系数" clearable>
            <template slot="append">倍</template>
          </el-input>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveUser">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import UserApi from '@/api/userManage'
import roleApi from '@/api/role'

export default {
  name: 'UserManagement',
  data() {
    const validateNumber = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('工时系数不能为空'))
      }
      setTimeout(() => {
        if (!/^\d+(\.\d+)?$/.test(value)) {
          callback(new Error('请输入数字'))
        } else {
          callback()
        }
      }, 300)
    }

    return {
      searchModel: {
        username: '',
        state: '',
        state_list: [
          { value: '', label: '全部' },  // 添加全部选项
          { value: '0', label: '在职' },
          { value: '1', label: '离职' },
        ],
        role: '',
        role_list: [],
        pageNo: 1,
        pageSize: 10,
        pageSizes: [5, 10, 20, 50],
      },
      total: 0,
      userList: [],
      listLoading: false,
      title: '',
      dialogFormVisible: false,
      userForm: {},
      rules: {
        username: [
          { required: true, message: '请输入员工姓名', trigger: 'blur' },
          { min: 2, max: 10, message: '长度在2到10个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 20, message: '长度在6到20个字符', trigger: 'blur' }
        ],
        gs: [
          { required: true, validator: validateNumber, trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    openEditUI(id) {
      if (id == null) {
        this.title = "新增员工"
        this.userForm = {
          state: '0' // 默认在职状态
        }
      } else {
        this.title = "编辑员工"
        this.listLoading = true
        UserApi.getUserById(id).then(response => {
          this.userForm = response.data.userInfo
        }).finally(() => {
          this.listLoading = false
        })
      }
      this.dialogFormVisible = true
    },
    handleSizeChange(pageSize) {
      this.searchModel.pageSize = pageSize
      this.getUserList()
    },
    handleCurrentChange(pageNo) {
      this.searchModel.pageNo = pageNo
      this.getUserList()
    },
    getUserList() {
      this.listLoading = true
      
      UserApi.getUserList(this.searchModel).then(response => {
        this.userList = response.data.userList.data
        this.total = response.data.userList.total
      }).catch(() => {
        this.userList = []
        this.total = 0
      }).finally(() => {
        this.listLoading = false
      })
    },
    getAllRoles() {
      roleApi.getAllRoles().then(response => {
        this.searchModel.role_list = response.data.allRolesList
      })
    },
    saveUser() {
      this.$refs.userFormRef.validate(valid => {
        if (valid) {
          this.listLoading = true
          UserApi.saveUser(this.userForm).then(response => {
            this.$message.success(response.message)
            this.dialogFormVisible = false
            this.getUserList()
          }).finally(() => {
            this.listLoading = false
          })
        }
      })
    },
    deleteUser(user) {
      this.$confirm(`确定要删除员工 ${user.username} 吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        center: true
      }).then(() => {
        this.listLoading = true
        UserApi.deleteUser(user.id).then(response => {
          this.$message.success(response.message)
          this.getUserList()
        }).finally(() => {
          this.listLoading = false
        })
      }).catch(() => {
        this.$message.info('已取消删除')
      })
    },
    clearForm() {
      this.userForm = {}
      this.$refs.userFormRef.clearValidate()
    },
    resetSearch() {
      this.searchModel.username = ''
      this.searchModel.state = ''
      this.searchModel.role = ''
      this.searchModel.pageNo = 1
      this.getUserList()
    }
  },
  created() {
    this.getAllRoles()
    this.getUserList()
  }
}
</script>

<style lang="scss" scoped>
.user-management-container {
  padding: 20px;

  .search-card {
    margin-bottom: 20px;

    .search-form {
      display: flex;
      align-items: center;
    }
  }

  .operation-area {
    margin-bottom: 20px;
  }

  .table-card {
    margin-bottom: 20px;

    .el-table {
      font-size: 14px;
    }
  }

  .pagination-area {
    display: flex;
    justify-content: flex-end;
  }
}

.el-dialog {
  .el-form-item {
    margin-bottom: 22px;
  }

  .el-input__inner {
    height: 38px;
    line-height: 38px;
  }

  .el-select {
    width: 100%;
  }
}

.el-avatar {
  background-color: #409EFF;
  color: white;
  font-weight: bold;
}
</style>